package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.AttributeMapper;
import cn.tedu.csmall.product.pojo.entity.Attribute;
import cn.tedu.csmall.product.pojo.param.AttributeAddNewParam;
import cn.tedu.csmall.product.pojo.vo.AttributeListItemVO;
import cn.tedu.csmall.product.pojo.vo.AttributeStandardVO;
import cn.tedu.csmall.product.service.IAttributeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AttributeServiceImpl implements IAttributeService {

    @Autowired
    private AttributeMapper attributeMapper;

    @Override
    public void addNew(AttributeAddNewParam attributeAddNewParam) {
        
        log.info("AlbumServiceImpl.addNew开始执行");
        
        log.debug("开始处理【添加属性】的业务，参数：{}" ,attributeAddNewParam);
        QueryWrapper<Attribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",attributeAddNewParam.getName()); //name='测试'
        int countByName = attributeMapper.selectCount(queryWrapper);
        log.debug("根据属性名称统计匹配的属性数量，结果：{}" ,countByName);
        if(countByName > 0 ){
            String message = "添加属性失败，属性名称已经被占用！";
//            System.out.println(message);
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //将属性数据写入到数据库中
        Attribute attribute = new Attribute();
        BeanUtils.copyProperties(attributeAddNewParam, attribute);
        attribute.setIsAllowCustomize(0);
        attribute.setGmtCreate(LocalDateTime.now());
        attribute.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的属性数据写入到数据库，数据：{}",attribute);
        attributeMapper.insert(attribute);
        log.debug("将新的属性数据写入到数据库，完成！");

    }

    @Override
    public PageData<AttributeListItemVO> listByTemplateId(Long templateId) {

        Integer pageNum = 1;
        log.debug("开始处理【根据属性模板查询属性列表】的业务，属性模板：{}, 页码：{}", templateId, pageNum);
        PageData<AttributeListItemVO> pageData = attributeMapper.listByTemplateId(templateId, pageNum, Integer.MAX_VALUE);
        return pageData;
    }



    @Override
    public AttributeStandardVO getStandardById(Long id) {


        log.debug("开始处理【根据id查询属性详情】的业务，参数：{}", id);
        AttributeStandardVO attribute = attributeMapper.getStandardById(id);
        if (attribute == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERROR_NOT_FOUND)
            String message = "查询属性详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return attribute;
    }
}
